package com.fenqing.leetcode.code.t300_400;

import com.fenqing.annotations.DesignClass;
import com.fenqing.core.design.DesignTopic;

import java.util.*;

/**
 * @author fenqing
 */
public class Topic380 extends DesignTopic {

    public Topic380(String methods, String params) {
        super(methods, params);
    }

    @DesignClass
    public static class RandomizedSet {

        Map<Integer, Integer> hash;

        int[] ids;

        int idx;

        private final Random random;

        public RandomizedSet() {
            hash = new HashMap<>();
            ids = new int[200010];
            random = new Random();
            idx = -1;
        }

        public boolean insert(int val) {
            if (hash.containsKey(val)) {
                return false;
            }
            idx++;
            hash.put(val, idx);
            ids[idx] = val;
            return true;
        }

        public boolean remove(int val) {
            if (hash.containsKey(val)) {
                Integer index = hash.remove(val);
                if (index != idx) {
                    hash.put(ids[idx], index);
                    ids[index] = ids[idx];
                }
                idx--;
                return true;
            }
            return false;
        }

        public int getRandom() {
            return ids[random.nextInt(idx + 1)];
        }
    }

    public static void main(String[] args) {
        Topic380 topic380 = new Topic380("""
                ["RandomizedSet","insert","remove","insert","remove","getRandom","getRandom","getRandom","getRandom","getRandom","getRandom","getRandom","getRandom","getRandom","getRandom"]
                                                                                          
                """, """
               [[],[0],[0],[-1],[0],[],[],[],[],[],[],[],[],[],[]]
                """);
        System.out.println(topic380.run());
    }
}
